package com.yimi.yinhepda.views.unload_module;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.entity.request.QueryUnloadTaskRequest;
import com.yimi.yinhepda.entity.response.QueryUnloadTask;
import com.yimi.yinhepda.entity.response.QueryUnloadTaskResponse;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.BarCodeRules;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.FastClick;
import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.views.load_module.LoadUnloadGroupActivity;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 卸车扫描界面
 *
 * @author 000432
 */
@SuppressWarnings("ResourceType")
public class CreateUnloadTaskActivity extends BaseActivity implements TextWatcher {
    private TextView num;
    private EditText carCode;
    /**
     * 车牌号
     */
    private TextView carNo;
    /**
     * 上一站
     */
    private TextView deptCode;
    /**
     * 总票数
     */
    private TextView totlePiao;
    private LinearLayout groupLayout, carCodeLayout;
    /**
     * 添加布局的计数器，根据需求应当《=5；
     */
    private int carCodeLayoutCount = 0;
    private static final int LAYOUT_ONE = 1;
    private static final int LAYOUT_TWO = 2;
    private static final int LAYOUT_THREE = 3;
    private static final int LAYOUT_FOUR = 4;
    /**
     * 总票
     */
    private int totlePrice;
    /**
     * 总件
     */
    private int totlePiece;
    /**
     * 已经下载数据的车标号
     */
    protected ArrayList<QueryUnloadTask> downloadCarCodes;
    /**
     * 上一站
     */
    private Set<String> preStations = new HashSet<>();
    /**
     * 下一站
     */
    private List<String> mCurrentDeptCodes = new ArrayList<>();
    /**
     * 登录部门类型
     */
    private int mDeptType;
    /**
     * 临时转换的配载单号
     */
    private String mTempStowage = "";

    @Override
    protected void handleBarCode(String result) {
        super.handleBarCode(result);

        if (!StringUtils.isCarCodeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("配载单号错误！");
            return;
        }
        //验证内存中是否存在
        for (QueryUnloadTask item : downloadCarCodes) {
            if (item.getStowageNo().equals(result)) {
                SoundVibratorManager.playSound(2);
                showToast("配载单号：" + result + "已扫描！");
                return;
            }
        }

        //验证数据库中是否存在
        UnloadTaskTableDao mUnloadTaskTableDao = new UnloadTaskTableDao();
        if (mUnloadTaskTableDao.findStowageNo(sharedPreferUtil.getValue(Common.USER_CODE), result)) {
            SoundVibratorManager.playSound(2);
            showToast("配载单号：" + result + "已扫描,已完成或已暂存！");
            return;
        }

        int currentIndex;
        EditText tmpText = null;
        switch (downloadCarCodes.size()) {
            case 0:
                carCode.setText(result);
                tmpText = carCode;
                break;
            case 1:
                currentIndex = 1;
                carCodeLayout = findViewById(Integer.valueOf(LAYOUT_ONE));
                EditText carCode1 = null;
                if (carCodeLayout != null) {
                    carCode1 = (EditText) carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                }

                if (carCode1 == null) {
                    carCodeLayout = (LinearLayout) LayoutInflater.from(CreateUnloadTaskActivity.this).inflate(R.layout.car_code_item, null);
                    ((TextView) carCodeLayout.findViewById(R.id.create_unload_task_name_item)).setText("配载单" + (currentIndex + 1) + "：");
                    ImageView pullImg = (ImageView) carCodeLayout.findViewById(R.id.create_unload_task_imgpull_item);
                    pullImg.setOnClickListener(CreateUnloadTaskActivity.this);
                    pullImg.setId(currentIndex);
                    carCodeLayout.setId(currentIndex);
                    groupLayout.addView(carCodeLayout, currentIndex);
                    carCodeLayoutCount++;
                    carCode1 = (EditText) carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                }
                carCode1.setText(result);
                tmpText = carCode1;
                break;
            case 2:
                currentIndex = 2;
                carCodeLayout = findViewById(Integer.valueOf(LAYOUT_TWO));
                EditText carCode2 = null;
                if (carCodeLayout != null) {
                    carCode2 = (EditText) carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                }
                if (carCode2 == null) {
                    carCodeLayout = (LinearLayout) LayoutInflater.from(CreateUnloadTaskActivity.this).inflate(R.layout.car_code_item, null);
                    ((TextView) carCodeLayout.findViewById(R.id.create_unload_task_name_item)).setText("配载单" + (currentIndex + 1) + "：");
                    ImageView pullImg = (ImageView) carCodeLayout.findViewById(R.id.create_unload_task_imgpull_item);
                    pullImg.setOnClickListener(CreateUnloadTaskActivity.this);
                    pullImg.setId(currentIndex);
                    carCodeLayout.setId(currentIndex);
                    groupLayout.addView(carCodeLayout, currentIndex);
                    carCodeLayoutCount++;
                    carCode2 = (EditText) carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                }
                carCode2.setText(result);
                tmpText = carCode2;
                break;
            case 3:
                currentIndex = 3;
                carCodeLayout = findViewById(Integer.valueOf(LAYOUT_THREE));
                EditText carCode3 = null;
                if (carCodeLayout != null) {
                    carCode3 = (EditText) carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                }

                if (carCode3 == null) {
                    carCodeLayout = (LinearLayout) LayoutInflater.from(CreateUnloadTaskActivity.this).inflate(R.layout.car_code_item, null);
                    ((TextView) carCodeLayout.findViewById(R.id.create_unload_task_name_item)).setText("配载单" + (currentIndex + 1) + "：");
                    ImageView pullImg = (ImageView) carCodeLayout.findViewById(R.id.create_unload_task_imgpull_item);
                    pullImg.setOnClickListener(CreateUnloadTaskActivity.this);
                    pullImg.setId(currentIndex);
                    carCodeLayout.setId(currentIndex);
                    groupLayout.addView(carCodeLayout, currentIndex);
                    carCodeLayoutCount++;
                    carCode3 = (EditText) carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                }
                carCode3.setText(result);
                tmpText = carCode3;
                break;
            case 4:
                currentIndex = 4;
                carCodeLayout = findViewById(Integer.valueOf(LAYOUT_FOUR));
                EditText carCode4 = null;
                if (carCodeLayout != null) {
                    carCode4 = (EditText) carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                }

                if (carCode4 == null) {
                    carCodeLayout = (LinearLayout) LayoutInflater.from(CreateUnloadTaskActivity.this).inflate(R.layout.car_code_item, null);
                    ((TextView) carCodeLayout.findViewById(R.id.create_unload_task_name_item)).setText("配载单" + (currentIndex + 1) + "：");
                    ImageView pullImg = (ImageView) carCodeLayout.findViewById(R.id.create_unload_task_imgpull_item);
                    pullImg.setOnClickListener(CreateUnloadTaskActivity.this);
                    pullImg.setId(currentIndex);
                    carCodeLayout.setId(currentIndex);
                    groupLayout.addView(carCodeLayout, currentIndex);
                    carCodeLayoutCount++;
                    carCode4 = (EditText) carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                }
                carCode4.setText(result);
                tmpText = carCode4;
                break;
            default:
                SoundVibratorManager.playSound(2);
                showToast("最多添加4个配载单");
                return;
        }

        downLoadData(result, tmpText);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_unload_task);
        initView();
        initValue();
    }

    public CreateUnloadTaskActivity() {
        super(true);
    }

    public void initView() {
        groupLayout = findViewById(R.id.layout_group);
        TextView title = findViewById(R.id.title);
        num = findViewById(R.id.num);
        title.setText("新建卸车任务");
        carCode = (EditText) findViewById(R.id.create_unload_task_carcode);
        carCode.addTextChangedListener(this);
        carNo = (TextView) findViewById(R.id.carNo);
        deptCode = (TextView) findViewById(R.id.dept_code);
        totlePiao = (TextView) findViewById(R.id.create_unload_total_piao);
        findViewById(R.id.create_unload_task_imgpull).setOnClickListener(this);
        findViewById(R.id.create_unload_task_arrive).setOnClickListener(this);
        findViewById(R.id.create_unload_task_back).setOnClickListener(this);
        //添加配载单
        findViewById(R.id.add_carCode).setOnClickListener(this);
        //删除配载单
        findViewById(R.id.del_carCode).setOnClickListener(this);
    }

    public void initValue() {
        mDeptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
        downloadCarCodes = new ArrayList<>();
        UnloadScanTableDao mUnloadScanTableDao = new UnloadScanTableDao();
        //设置未上传数
        num.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, 2) + "");
    }

    @Override
    public String getPageName() {
        return "新建卸车任务";
    }

    private void merge(final QueryUnloadTask model, final EditText carCode) {
        //目的站非本站的卸车，给出提示
        if (!model.getDestDeptCode().equals(SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE))) {
            SoundVibratorManager.playSound(2);
            MyDialog dialog = new MyDialog(this);
            dialog.setMessage("此配载单非本站卸车任务，是否继续卸车？");
            dialog.setPositiveClickListener( Constants.confirmMsg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    dotask(model, carCode);
                    //开启扫描
                    setScannerEnabled(true);
                }
            });
            dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //开启扫描
                    setScannerEnabled(true);
                }
            });
            dialog.show();
            return;
        }
        //开启扫描
        setScannerEnabled(true);
        dotask(model, carCode);
    }

    private void dotask(QueryUnloadTask model, EditText carCode) {
        //存储已下载的车标号
        if (!downloadCarCodes.contains(model)) {
            downloadCarCodes.add(model);
        } else {
            SoundVibratorManager.playSound(2);
            showToast("配载单号已下载，不能重复下载!");
            return;
        }
        SoundVibratorManager.playSound(1);
        //下一站信息（当前站）
        mCurrentDeptCodes.add(model.getDestDeptCode());
        if (TextUtils.isEmpty(deptCode.getText().toString())) {
            preStations.add(model.getSrcDeptName());
            //上一站信息
            deptCode.setText(model.getSrcDeptName());
        } else {
            //多个上站信息滚动显示
            preStations.add(model.getSrcDeptName());
            StringBuilder temp = new StringBuilder();
            for (String item : preStations) {
                temp.append(item + " ");
            }
            deptCode.setText(temp.toString());
        }
        if (!TextUtils.isEmpty(totlePiao.getText().toString())) {
            totlePrice += Integer.valueOf(model.getPriceNum());
            totlePiece += Integer.valueOf(model.getPiecesNum());

            //合并后票数和件数累加
            totlePiao.setText(totlePrice + "票/" + totlePiece + "件");
        } else {
            totlePrice = Integer.valueOf(model.getPriceNum());
            totlePiece = Integer.valueOf(model.getPiecesNum());
            totlePiao.setText(totlePrice + "票/" + totlePiece + "件");
        }
        if (carCode != null) {
            carCode.setEnabled(false);
        }
    }

    private void doUnloadTask(QueryUnloadTaskResponse entity, final EditText carCode) {
        if (entity != null) {
            if (!entity.getSuccess()) {
                SoundVibratorManager.playSound(2);
                if (entity.getErrorMessages() != null && entity.getErrorMessages().length > 0) {
                    showToast(entity.getErrorMessages()[0]);
                } else {
                    showToast("服务器返回下载失败，请联系管理人员!");
                }

                //开启扫描
                setScannerEnabled(true);
                return;
            }
            final QueryUnloadTask model = entity.getData();
            if (model == null) {
                SoundVibratorManager.playSound(2);
                showToast("配载单号数据为空!");
                //开启扫描
                setScannerEnabled(true);
                return;
            }
            Integer sealStatus = model.getSealStatus();
            if (sealStatus != null && (sealStatus == 1 || sealStatus == 2)) {
                MyDialog.showAlertDialog(this, "该配载单未解封，不能进行卸车操作");
                return;
            }

            if (TextUtils.isEmpty(carNo.getText().toString())) {
                carNo.setText(model.getCarNo());
            } else {
                //车牌号不一致
                if (!carNo.getText().toString().equals(model.getCarNo())) {
                    SoundVibratorManager.playSound(2);
                    MyDialog dialog = new MyDialog(this);
                    dialog.setMessage("与上一配载单车牌号不一致，是否继续合并?");
                    dialog.setPositiveClickListener( Constants.confirmMsg, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            merge(model, carCode);
                            //开启扫描
                            setScannerEnabled(true);
                        }
                    });
                    dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //开启扫描
                            setScannerEnabled(true);
                        }
                    });
                    dialog.show();
                    return;
                }
            }
            //合并配载单号数据
            merge(model, carCode);
        } else {
            //开启扫描
            setScannerEnabled(true);
            SoundVibratorManager.playSound(2);
            showToast("下载配载单号失败");
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        //防抖
        if (FastClick.isFastClick()) {
            return;
        }

        int currentIndex = carCodeLayoutCount;
        switch (v.getId()) {
            case R.id.add_carCode:
                //添加配载单布局
                if (++currentIndex > 4) {
                    showToast("最多添加4个配载单");
                    return;
                }
                carCodeLayout = (LinearLayout) LayoutInflater.from(CreateUnloadTaskActivity.this).inflate(R.layout.car_code_item, null);
                ((TextView) carCodeLayout.findViewById(R.id.create_unload_task_name_item)).setText("配载单" + (currentIndex + 1) + " ：");
                ImageView pullImg = (ImageView) carCodeLayout.findViewById(R.id.create_unload_task_imgpull_item);
                pullImg.setOnClickListener(CreateUnloadTaskActivity.this);
                pullImg.setId(currentIndex);
                carCodeLayout.setId(currentIndex);
                groupLayout.addView(carCodeLayout, currentIndex);
                carCodeLayoutCount++;

                break;
            case R.id.del_carCode:
                if (currentIndex < 1) {
                    showToast("至少存在一个配载单");
                    return;
                }
                LinearLayout delLayout = (LinearLayout) findViewById(currentIndex);
                final TextView delCarCode = (TextView) delLayout.findViewById(R.id.create_unload_task_carcode_item);
                if (!delCarCode.isEnabled()) {
                    for (QueryUnloadTask task : downloadCarCodes) {
                        if (task.getStowageNo().contains(delCarCode.getText().toString())) {
                            MyDialog dialog = new MyDialog(this);
                            dialog.setMessage("配载单号" + delCarCode.getText().toString() + "已经下载成功，是否删除？");
                            final int finalCurrentIndex = currentIndex;
                            dialog.setPositiveClickListener( Constants.confirmMsg, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    QueryUnloadTask model = downloadCarCodes.get(finalCurrentIndex);
                                    if (!TextUtils.isEmpty(totlePiao.getText().toString())) {
                                        totlePrice -= Integer.valueOf(model.getPriceNum());
                                        totlePiece -= Integer.valueOf(model.getPiecesNum());

                                        //合并后票数和件数累加
                                        totlePiao.setText(totlePrice + "票/" + totlePiece + "件");
                                    } else {
                                        totlePrice = Integer.valueOf(model.getPriceNum());
                                        totlePiece = Integer.valueOf(model.getPiecesNum());
                                        totlePiao.setText(totlePrice + "票/" + totlePiece + "件");
                                    }

                                    //确定删除要删除集合中的车标号
                                    downloadCarCodes.remove(finalCurrentIndex);
                                    groupLayout.removeViewAt(carCodeLayoutCount);
                                    carCodeLayoutCount--;
                                }
                            });
                            dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            dialog.show();
                            return;
                        }
                    }
                }
                groupLayout.removeViewAt(currentIndex);
                carCodeLayoutCount--;

                break;
            case R.id.create_unload_task_carcode_item:
                break;
            case LAYOUT_ONE:
                carCodeLayout = findViewById(Integer.valueOf(LAYOUT_ONE));
                EditText carCode1 = carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                checkCarCode(carCode1);
                break;
            case LAYOUT_TWO:
                carCodeLayout = findViewById(Integer.valueOf(LAYOUT_TWO));
                EditText carCode2 = carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                checkCarCode(carCode2);
                break;
            case LAYOUT_THREE:
                carCodeLayout = findViewById(Integer.valueOf(LAYOUT_THREE));
                EditText carCode3 = carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                checkCarCode(carCode3);
                break;
            case LAYOUT_FOUR:
                carCodeLayout = findViewById(Integer.valueOf(LAYOUT_FOUR));
                EditText carCode4 = carCodeLayout.findViewById(R.id.create_unload_task_carcode_item);
                checkCarCode(carCode4);
                break;
            case R.id.create_unload_task_imgpull:
                //下载配载单
                checkCarCode(carCode);
                break;
            case R.id.create_unload_task_arrive:
                if (downloadCarCodes == null || downloadCarCodes.isEmpty()) {
                    showToast("请先下载配载单号！");
                    return;
                }
                String task = Constants.getUUID();
                UnloadTaskTableDao mUnloadTaskTableDao = new UnloadTaskTableDao();
                try {
                    if (mUnloadTaskTableDao.insert(UnloadTaskTable.parse(task, downloadCarCodes)) > 0) {
                        Intent unloadScanIntent;
                        if (mDeptType == 5 || mDeptType == 6) {
                            //分拨才使用装卸组功能
                            unloadScanIntent = new Intent(CreateUnloadTaskActivity.this, LoadUnloadGroupActivity.class);
                        } else {
                            unloadScanIntent = new Intent(CreateUnloadTaskActivity.this, UnloadScanActivity.class);
                        }
                        Bundle bundle = new Bundle();
                        bundle.putString("carNo", carNo.getText().toString());
                        bundle.putString("task", task);
                        bundle.putString("deptCode", deptCode.getText().toString());
                        bundle.putSerializable("currentDeptCodes", (Serializable) mCurrentDeptCodes);
                        //扫描类型：1-装车扫描，2-卸车扫描
                        bundle.putInt("scanType", 2);
                        unloadScanIntent.putExtras(bundle);
                        startActivity(unloadScanIntent);
                        finish();
                        return;
                    }
                } catch (SQLException e) {
                    LogUtil.e(e.toString());
                    showToast("数据库插入数据失败：" + e.toString());
                }
                break;
            case R.id.create_unload_task_back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 校验配载单号
     */
    private void checkCarCode(EditText carCode) {
        String carCode1Str = carCode.getText().toString().trim();
        if (!TextUtils.isEmpty(carCode1Str)) {
            if (BarCodeRules.carCodeCheck(carCode1Str)) {
                carCode1Str = carCode1Str.toUpperCase();
                carCode.setText(carCode1Str);
                //根据配载单号下载卸车数据
                downLoadData(carCode1Str, carCode);
            } else {
                showToast("配载单号错误！");
            }
        } else {
            showToast("配载单号不能为空");
        }
    }

    /**
     * 根据配载单号下载卸车数据
     */
    public void downLoadData(String stowageNo, final EditText carCode) {
        //验证内存中是否存在
        for (QueryUnloadTask item : downloadCarCodes) {
            if (item.getStowageNo().equals(stowageNo)) {
                SoundVibratorManager.playSound(2);
                showToast("配置单号：" + stowageNo + "已扫描！");
                return;
            }
        }

        //验证数据库中是否存在
        UnloadTaskTableDao mUnloadTaskTableDao = new UnloadTaskTableDao();
        if (mUnloadTaskTableDao.findStowageNo(sharedPreferUtil.getValue(Common.USER_CODE), stowageNo)) {
            SoundVibratorManager.playSound(2);
            showToast("配置单号：" + stowageNo + "已扫描！");
            return;
        }

        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("下载配载单号中，请稍等...", false);
        QueryUnloadTaskRequest mQueryUnloadTaskRequest = new QueryUnloadTaskRequest();
        mQueryUnloadTaskRequest.setStowageNo(stowageNo);

        new NetRequest().setUrl(Constants.URL_GET_UNLOAD_TASK_DATA)
                .setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryUnloadTaskResponse.class)
                .setRequestObject(mQueryUnloadTaskRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        //开启扫描
                        setScannerEnabled(true);
                        SoundVibratorManager.playSound(2);
                        showToast("下载配载单号失败：" + msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        //关闭对话框
                        dismissPgDlg();
                        QueryUnloadTaskResponse response = (QueryUnloadTaskResponse) obj;
                        doUnloadTask(response, carCode);
                    }
                });
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        //英文字母转换成大写
        String carNo = carCode.getText().toString().toUpperCase();
        if (!carNo.equalsIgnoreCase(mTempStowage)) {
            mTempStowage = carNo;
            carCode.setText(carNo);
            carCode.setSelection(carNo.length());
        }
    }
}
